package org.journal.service;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Set;

import org.journal.dao.AuthoritiesDAO;
import org.journal.dao.UserDAO;
import org.journal.entity.AuthoritiesEntity;
import org.journal.entity.UserEntity;
import org.journal.security.Hasher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service
public class RegistrationServiceImpl implements RegistrationService {

	private static final Logger log = LoggerFactory
			.getLogger(RegistrationServiceImpl.class);

	private static final String USER_ROLE_AUTHORITY = "ROLE_USER";

	@Autowired
	private AuthoritiesDAO authoritiesDAO;

	@Autowired
	private UserDAO userDAO;

	public UserEntity checkUserExistence(String name) {
		return userDAO.getUserByName(name);
	}

	public UserEntity createUser(String username, String password) {

		AuthoritiesEntity authorities = null;
		UserEntity user = new UserEntity();
		user.setUsername(username);

		String hashedPass = Hasher.createHash(password);

		user.setPassword(hashedPass);
		user.setEnabled(true);
		user.setCreationDate(new GregorianCalendar());
		int userId = userDAO.createUser(user);
		
		user.setIdUser(userId);

		authorities = new AuthoritiesEntity(user, USER_ROLE_AUTHORITY);

		authoritiesDAO.createAuthorities(authorities);

		Set<AuthoritiesEntity> userRoles = new HashSet<AuthoritiesEntity>();
		userRoles.add(authorities);

		user.setAuthoritiesEntities(userRoles);
		return user;
	}
}
